

#ifdef WX_PRECOMP
#include "wx_pch.h"
#endif

#ifdef __BORLANDC__
#pragma hdrstop
#endif //__BORLANDC__

#include <wx/artprov.h>
#include <wx/fileconf.h>

#include <wx/log.h>

#include "MainFrame.h"

#include "ConfigWindow.h"
#include "TaskBarIcon.h"
#include "MessengerPanel.h"
#include "MessengerNotebook.h"
#include "SessionPanel.h"

#include "Util.h"
#include "GlobalConfig.h"
#include "UserConfig.h"

#include "MsnDef.h"
#include "MsnMessenger.h"

#include "../resource/xpm/page_new.xpm"
#include "../resource/xpm/page_close.xpm"

#include "../resource/xpm/logo_online.xpm"
//#include "../resource/xpm/logo_offline.xpm"
//#include "../resource/xpm/logo_newmsg.xpm"

#include "../resource/xpm/open_logs.xpm"
#include "../resource/xpm/options.xpm"

//#include "../resource/xpm/sample.xpm"

#define TUX_VERSION _T("0.3.0")

//helper functions
enum wxbuildinfoformat
{
    short_f, long_f
};

wxString wxbuildinfo(wxbuildinfoformat format)
{
    wxString wxbuild(TUX_VERSION);

#if defined(__WXMSW__)
        wxbuild << _T("-Windows build");
#elif defined(__UNIX__)
        wxbuild << _T("-Linux build");
#endif

    return wxbuild;
}

/*
#include <wx/hyperlink.h>

class AboutWindow : public wxDialog
{

public:
	AboutWindow(wxWindow* parent)
        :wxDialog(parent,-1,_T("About Tuxitty"),wxDefaultPosition,wxDefaultSize,wxSIMPLE_BORDER)
	{
		 wxString buildInfo = wxbuildinfo(long_f);

		wxStaticText* staticText1 = new wxStaticText(this, wxID_ANY, _T("Tuxitty - another msn client"));

		wxStaticText* staticText2 = new wxStaticText(this, wxID_ANY, buildInfo);

		wxHyperlinkCtrl* linkCtrl = new wxHyperlinkCtrl(this, -1, _T("tuxitty@hotmail.com"), _T("mailto:tuxitty@hotmail.com"));
	

		wxBoxSizer* sizer = new wxBoxSizer(wxVERTICAL);


		sizer->Add(staticText1, 0, wxLEFT|wxTOP, 3);
		sizer->Add(staticText2, 0, wxLEFT|wxTOP, 3);

		sizer->Add(linkCtrl, 0, wxLEFT|wxTOP, 3);

		//sizer->Add(okButton, 0, wxALL|wxALIGN_CENTER, 5);

		SetSizer(sizer);

		Fit();
	}
};
*/

int ID_MENU_FILE_NEW_PAGE = wxNewId();
int ID_MENU_FILE_CLOSE_PAGE = wxNewId();
int ID_MENU_FILE_CLOSE_ALL = wxNewId();

int ID_MENU_FILE_SIGNOUT = wxNewId();

int ID_MENU_TOOL_OPTIONS = wxNewId();
int ID_MENU_TOOL_OPEN_TRANSFER_WINDOW = wxNewId();
int ID_MENU_TOOL_OPEN_HISTORY_FOLDER = wxNewId();
int ID_MENU_TOOL_OPEN_FILE_FOLDER = wxNewId(); 

int ID_MENU_CONTACT_ADD_CONTACT = wxNewId(); 
int ID_MENU_CONTACT_ADD_GROUP = wxNewId(); 

int ID_MENU_LANGUAGE_CHINESE = wxNewId();
int ID_MENU_LANGUAGE_ENGLISH = wxNewId();


int ID_TOOL_NEW_PAGE = wxNewId();
int ID_TOOL_CLOSE_PAGE = wxNewId();

int ID_TOOL_OPTIONS = wxNewId(); 

int ID_TOOL_TRANSFER_WINDOW = wxNewId(); 


int ID_TIMER_STATUS_CLEANER =wxNewId();


int ID_MENU_FILE_STATUS = 10000;

int ID_MENU_CONTACTS_RECENT = 10100;



//int ID_MENU_CONTACTS_NEWLY_ADDED = 10200;

DEFINE_EVENT_TYPE(tuxEVT_LOG);

BEGIN_EVENT_TABLE(MainFrame, wxFrame)

	EVT_CLOSE(                                 MainFrame::OnClose)

    EVT_TIMER(ID_TIMER_STATUS_CLEANER,         MainFrame::OnMainTimer)

    //EVT_MENU_RANGE(ID_MENU_FILE_STATUS, ID_MENU_FILE_STATUS + MsnDef::STATUS_COUNT, MainFrame::OnChangeStatus)

	EVT_ACTIVATE(MainFrame::OnActivate) 

	
	EVT_MENU(ID_MENU_FILE_NEW_PAGE,              MainFrame::OnNewPage)
	
	EVT_MENU(ID_MENU_FILE_CLOSE_PAGE,             MainFrame::OnClosePage)
	EVT_MENU(ID_MENU_FILE_CLOSE_ALL,         MainFrame::OnCloseAll)

	EVT_MENU(ID_MENU_FILE_SIGNOUT,         MainFrame::OnSignOut)

    EVT_MENU(ID_MENU_FILE_QUIT,                MainFrame::OnQuit)


    EVT_MENU_RANGE(ID_MENU_CONTACTS_RECENT, ID_MENU_CONTACTS_RECENT + 10, MainFrame::OnRecentContact)


	EVT_MENU(ID_MENU_TOOL_OPTIONS,            MainFrame::OnOptions)
	
	EVT_MENU(ID_MENU_TOOL_OPEN_TRANSFER_WINDOW,    MainFrame::OnTransferWindow)

	EVT_MENU(ID_MENU_TOOL_OPEN_HISTORY_FOLDER,		   MainFrame::OnOpenMessageHistoryFolder)
    EVT_MENU(ID_MENU_TOOL_OPEN_FILE_FOLDER,        MainFrame::OnOpenReceivedFileFolder)

	EVT_MENU(ID_MENU_LANGUAGE_CHINESE,		   MainFrame::OnLanguage)
    EVT_MENU(ID_MENU_LANGUAGE_ENGLISH,         MainFrame::OnLanguage)

	EVT_NOTEBOOK_PAGE_CHANGED(wxID_ANY,			MainFrame::OnMessengerPanelChanged)

	EVT_MENU(ID_MENU_CONTACT_ADD_CONTACT,        MainFrame::OnAddContact)
	EVT_MENU(ID_MENU_CONTACT_ADD_GROUP,        MainFrame::OnAddGroup)
	
	EVT_COMMAND(wxID_ANY, EVT_MESSENGER_PANEL_CLOSED, MainFrame::OnMessengerPanelClosed)


	EVT_MENU(ID_MENU_HELP_TEST,                MainFrame::OnTest)
	EVT_MENU(ID_MENU_HELP_TEST_PROXY,          MainFrame::OnTestProxy)
	
    EVT_MENU(ID_MENU_HELP_DEBUG,               MainFrame::OnDebug)
	EVT_COMMAND(wxID_ANY, EVT_DEBUG_RECEIVED,     MainFrame::OnDebugReceived)
	
    EVT_MENU(ID_MENU_HELP_ABOUT,               MainFrame::OnAbout)

	
	EVT_TOOL(ID_TOOL_NEW_PAGE,					  MainFrame::OnNewPage)
    EVT_TOOL(ID_TOOL_CLOSE_PAGE,                  MainFrame::OnClosePage)
	

	EVT_TOOL(ID_TOOL_OPTIONS,					MainFrame::OnOptions)
	EVT_TOOL(ID_TOOL_TRANSFER_WINDOW,           MainFrame::OnTransferWindow)
	

    EVT_COMBOBOX(-1,							MainFrame::OnToolSearch)

END_EVENT_TABLE()

MainFrame::MainFrame(wxFrame *frame, const wxString& title, const wxPoint& pos, const wxSize& size)
    : wxFrame(frame, -1, title, pos, size, wxDEFAULT_FRAME_STYLE), 
		menuBar(NULL),toolBar(NULL), messengerNotebook(NULL), logWindow(NULL),
		isIdle(false)
{
	
	taskBarIcon = new TaskBarIcon(this);

    CreateMenuBar();

	CreateToolBar();

	CreateNotebook();

	//SetBackgroundColour(*wxLIGHT_GREY);  

    CreateStatusBar(3);
    //SetStatusText(_("Tuxitty"),0);

//    UpdateUIStatus();


	//TODO use SetIcons 
	//SetIcon(wxIcon(sample_xpm));
	SetIcon(wxIcon(logo_online_xpm));

	//wxIcon logo(_T("tux.gif"), wxBITMAP_TYPE_GIF);
	//SetIcon(logo);
	
	//wxIconBundle iconBundle;
	//iconBundle.AddIcon(logo);	
	//SetIcons((iconBundle));

	lastStatusUpdate = 0;
	mainTimer = new wxTimer(this, ID_TIMER_STATUS_CLEANER);
	mainTimer->Start(1000);

}

MainFrame::~MainFrame()
{
	mainTimer->Stop();

	wxDELETE(mainTimer);
    wxDELETE(taskBarIcon);
}

void MainFrame::CreateUI()
{
	CreateMenuBar();
	CreateToolBar();
}


void MainFrame::CreateMenuBar()
{
    menuBar = new wxMenuBar();

    wxMenu* fileMenu = new wxMenu;

	fileMenu->Append(ID_MENU_FILE_NEW_PAGE, _("New"));
    fileMenu->Append(ID_MENU_FILE_CLOSE_PAGE, _("Close"));
	fileMenu->Append(ID_MENU_FILE_CLOSE_ALL, _("Close All"));
    fileMenu->AppendSeparator();

	fileMenu->Append(ID_MENU_FILE_SIGNOUT, _("Sign Out"));
	fileMenu->AppendSeparator();
    
    fileMenu->Append(ID_MENU_FILE_QUIT, _("&Quit\tAlt-F4"));
    menuBar->Append(fileMenu, _("&File"));

	wxMenu* contactMenu = new wxMenu;
	contactMenu->Append(ID_MENU_CONTACT_ADD_CONTACT, _("Add Contact"));
	contactMenu->Append(ID_MENU_CONTACT_ADD_GROUP, _("Add Group"));

	 menuBar->Append(contactMenu,_("&Contact"));

    wxMenu* actionMenu = new wxMenu;
	actionMenu->Append(ID_MENU_TOOL_OPTIONS, _("Options"));
    
	actionMenu->AppendSeparator();
	actionMenu->Append(ID_MENU_TOOL_OPEN_FILE_FOLDER, _("Open Received File Folder"));
	actionMenu->Append(ID_MENU_TOOL_OPEN_HISTORY_FOLDER, _("Open Message History Folder"));

    menuBar->Append(actionMenu,_("&Tools"));

	//language menu
	wxMenu* langMenu = new wxMenu;
	langMenu->AppendRadioItem(ID_MENU_LANGUAGE_CHINESE, _("Chinese"));
	langMenu->AppendRadioItem(ID_MENU_LANGUAGE_ENGLISH, _("English"));

    menuBar->Append(langMenu,_("Language"));
	CheckLanguageMenu(langMenu);

	//help menu
    wxMenu* helpMenu = new wxMenu;
    helpMenu->Append(ID_MENU_HELP_ABOUT, _("About"));
    menuBar->Append(helpMenu, _("&Help"));

#ifdef _DEBUG
	wxMenu* testMenu = new wxMenu;
	testMenu->Append(ID_MENU_HELP_TEST, _T("Test"));
	testMenu->Append(ID_MENU_HELP_TEST_PROXY, _T("Test Proxy"));
	testMenu->Append(ID_MENU_HELP_DEBUG, _T("Debug"));
	menuBar->Append(testMenu, _T("&Test"));

#endif

    SetMenuBar(menuBar);
}

void MainFrame::CreateToolBar()
{
    toolBar = new wxToolBar(this, wxID_ANY, wxDefaultPosition, wxDefaultSize, wxTB_FLAT);

    toolBar->SetToolBitmapSize(wxSize(16,16));

	toolBar->AddTool(ID_TOOL_NEW_PAGE, _T(""), wxBitmap(page_new_xpm), _("New"));
    toolBar->AddTool(ID_TOOL_CLOSE_PAGE, _T(""), wxBitmap(page_close_xpm), _("Close"));


	toolBar->AddSeparator();

	toolBar->AddTool(ID_TOOL_OPTIONS, _T(""), wxBitmap(options_xpm), _("Options"));
	//toolBar->AddTool(ID_TOOL_TRANSFER_WINDOW, _T(""), wxBitmap(open_logs_xpm), _("Open File Transfer Window"));

/*
    toolBar->AddSeparator();

    m_SearchTextCtrl
        = new wxTextCtrl(toolBar, wxID_ANY, _T("search..."),wxDefaultPosition, wxSize(200, wxDefaultCoord), wxTE_PROCESS_ENTER|wxWANTS_CHARS);
    m_SearchComboBox
        = new wxOwnerDrawnComboBox(toolBar, ID_TOOL_SEARCH, _T(""), wxDefaultPosition, wxSize(60, wxDefaultCoord), NULL, wxNO_BORDER | wxCB_READONLY);

    wxBitmap buttonImage(_T("images/combo_button.gif"), wxBITMAP_TYPE_GIF);
    m_SearchComboBox->SetButtonBitmaps(buttonImage, false);

    m_SearchComboBox->SetCustomPaintWidth(0);

    m_SearchComboBox->Append(_T("google"));
    m_SearchComboBox->Append(_T("answer"));

    m_SearchComboBox->SetText(_T("search"));

    toolBar->AddControl(m_SearchTextCtrl);
    toolBar->AddControl(m_SearchComboBox);
*/

    toolBar->Realize();
    SetToolBar(toolBar);
}

void MainFrame::CreateNotebook()
{
	messengerNotebook = new MessengerNotebook(this);
	messengerNotebook->CreateMessengerPanel();
}

void MainFrame::CheckLanguageMenu(wxMenu* langMenu)
{
	int lang = GlobalConfig::GetLanguage();
	switch (lang){
		case wxLANGUAGE_ENGLISH: langMenu->Check(ID_MENU_LANGUAGE_ENGLISH, true); break;
		case wxLANGUAGE_CHINESE_SIMPLIFIED: langMenu->Check(ID_MENU_LANGUAGE_CHINESE, true); break;
	}
}

void MainFrame::UpdateUIText()
{
	RecreateMenuBar();
	RecreateToolBar();

	if(messengerNotebook != NULL){
		for(unsigned int i=0;i<messengerNotebook->GetPageCount();i++){
			MessengerPanel* panel = (MessengerPanel*)messengerNotebook->GetPage(i);
			panel->UpdateUIText();

			if(!panel->IsAlive()){
				messengerNotebook->SetPageText(i, _("New Page"));
			}
		}	
	}	
}

void MainFrame::UpdateUIStatus()
{
	MessengerPanel* panel = GetCurrentMessengerPanel();

	if(panel != NULL && panel->IsAlive()){	

		menuBar->Enable(ID_MENU_FILE_SIGNOUT, true); 

		menuBar->Enable(ID_MENU_CONTACT_ADD_CONTACT, true); 
		menuBar->Enable(ID_MENU_CONTACT_ADD_GROUP, true); 

		//menuBar->Enable(ID_MENU_TOOL_OPTIONS, true); 
		menuBar->Enable(ID_MENU_TOOL_OPEN_FILE_FOLDER, true);
		menuBar->Enable(ID_MENU_TOOL_OPEN_HISTORY_FOLDER, true);			

	}else{

		menuBar->Enable(ID_MENU_FILE_SIGNOUT, false);

		menuBar->Enable(ID_MENU_CONTACT_ADD_CONTACT, false); 
		menuBar->Enable(ID_MENU_CONTACT_ADD_GROUP, false); 


		menuBar->Enable(ID_MENU_TOOL_OPEN_FILE_FOLDER, false);
		menuBar->Enable(ID_MENU_TOOL_OPEN_HISTORY_FOLDER, false);	

	}

	if(messengerNotebook->GetPageCount() > 0){
		menuBar->Enable(ID_MENU_FILE_CLOSE_PAGE, true);
		menuBar->Enable(ID_MENU_FILE_CLOSE_ALL, true);    

		toolBar->EnableTool(ID_TOOL_CLOSE_PAGE, true);	
		
	}else{
		menuBar->Enable(ID_MENU_FILE_CLOSE_PAGE, false);
		menuBar->Enable(ID_MENU_FILE_CLOSE_ALL, false);	

		toolBar->EnableTool(ID_TOOL_CLOSE_PAGE, false);		
	}
}

void MainFrame::UpdateTaskBarIcon()
{
	wxIcon logo;
	if(this->IsOnline()){		
		//logo = wxIcon(logo_online_xpm);
	}else{
		//logo = wxIcon(logo_offline_xpm);
	}	

	//taskBarIcon->SetIcon(logo);
	//this->SetIcon(logo);
}

void MainFrame::UpdateStatusBarText(const wxString& text)
{
	//time_t now = wxDateTime::GetTimeNow();
	lastStatusUpdate = wxDateTime::GetTimeNow();
	this->SetStatusText(text, 1);
}

void MainFrame::RecreateMenuBar()
{
	wxMenuBar *oldmenubar = menuBar;
    
	CreateMenuBar();

	wxDELETE(oldmenubar);
}

void MainFrame::RecreateToolBar()
{
	wxToolBar* oldToolBar = toolBar;

	CreateToolBar();

	wxDELETE(oldToolBar);
}

MessengerPanel* MainFrame::GetCurrentMessengerPanel()
{
	return (MessengerPanel*)messengerNotebook->GetCurrentPage();
}

MsnMessenger* MainFrame::GetCurrentMessenger()
{
	MessengerPanel* panel = GetCurrentMessengerPanel();
	if(panel != NULL){
		return panel->GetMessenger();
	}

	return NULL;
}

bool MainFrame::IsOnline()
{
	for(unsigned int i=0; i < messengerNotebook->GetPageCount(); i++){		
		MessengerPanel* panel = (MessengerPanel*)messengerNotebook->GetPage(i);
		if(panel->IsAlive())
			return true;
    }	

	return false;
}

bool MainFrame::HasNewMessage()
{
	for(unsigned int i=0; i < messengerNotebook->GetPageCount(); i++){		
		MessengerPanel* panel = (MessengerPanel*)messengerNotebook->GetPage(i);
		if(panel->HasNewMessage())
			return true;
    }	

	return false;

}


void MainFrame::UpdateUIWhenUserSignIn()
{
	UpdateUIStatus();
	UpdateTaskBarIcon();
}

void MainFrame::UpdateUIWhenUserSignOut()
{
	UpdateUIStatus();
	UpdateTaskBarIcon();
}

void MainFrame::UpdateUIWhenNewMsgArrive()
{
	DEBUG(_T("UpdateUIWhenNewMsgArrive"));

	if(!this->IsActive()){
		DEBUG(_T("request user attention"));
        this->RequestUserAttention();
	}

	//check the current panel
	if(this->IsActive() && this->IsShown()){
		this->GetCurrentMessengerPanel()->CurrentSessionPanel()->SetNewMessage(false);
	}


	/*
	if(!wxGetApp().IsActive()){
		DEBUG(_T("request user attention"));
        ((wxFrame*)(wxGetApp().GetTopWindow()))->RequestUserAttention();
	}
	*/
}

void MainFrame::OnMainTimer(wxTimerEvent& e)
{
	time_t now = wxDateTime::GetTimeNow();

	//check if there's new messages
	if(HasNewMessage()){
		//flash icon on taskbar
		taskBarIcon->SwitchIconForNewMessage();
	}else{
		if(taskBarIcon->ShowNewMsg()){
			//restore the icon
			taskBarIcon->SwitchIconForNewMessage();
		}
	}

	//clean status bar
	if(now - lastStatusUpdate > 5){
		UpdateStatusBarText(_T(""));
	}

	//check idle time
	int idleTime = SystemUtil::GetIdleTime();
	//DEBUG(wxString::Format(_T("idle time: %d"), idleTime));


	//TODO configuration
	if(idleTime > 30){
		if(!isIdle){
			isIdle = true;
			ChangeStatusToIdle(isIdle);
		}
	}else{
		if(isIdle){
			isIdle = false;
			ChangeStatusToIdle(isIdle);
		}
	}

}

void MainFrame::ChangeStatusToIdle(bool isIdle)
{
	for(unsigned int i=0; i < messengerNotebook->GetPageCount(); i++){		
		MessengerPanel* panel = (MessengerPanel*)messengerNotebook->GetPage(i);
		if(panel->GetMessenger()->IsAlive()){
			panel->GetMessenger()->ChangeStatusToIdle(isIdle);
		}
	}
}


void MainFrame::OnNewPage(wxCommandEvent& event)
{
	messengerNotebook->CreateMessengerPanel();
}
        

void MainFrame::OnClosePage(wxCommandEvent& event)
{
	int selection = messengerNotebook->GetSelection();

	if(selection > -1){
		MessengerPanel* panel = (MessengerPanel*)messengerNotebook->GetPage(selection);

/*   confirm for closing
		if(panel->GetMessenger()->IsOnline()){
			wxMessageDialog dialog(NULL, _T("The messenger is still online, continue?"), _T("Close Messenger"), wxYES_NO);

			switch(dialog.ShowModal()){
				case wxID_YES:
					break;
				case wxID_NO:
					return;
			}
		}
*/

		messengerNotebook->DeletePage(selection);
	}
		
}

void MainFrame::OnAddContact(wxCommandEvent& event)
{
	wxTextEntryDialog dialog(this, _("Enter the email:"), _("Add Contact"), _T(""), wxOK|wxCANCEL);
    if(dialog.ShowModal() == wxID_OK){
        wxString email = dialog.GetValue();
		if(!email.IsEmpty() && GetCurrentMessenger()->IsAlive()){
			GetCurrentMessenger()->AddContactToForwardList(email);
			GetCurrentMessenger()->AddContactToAllowedList(email);
		}
    }	
}
  

void MainFrame::OnAddGroup(wxCommandEvent& event)
{

	wxTextEntryDialog dialog(this, _("Enter the group name:"), _T("Add Group"), _T(""), wxOK|wxCANCEL);
    if(dialog.ShowModal() == wxID_OK){
        wxString name = dialog.GetValue();
		if(!name.IsEmpty() && GetCurrentMessenger()->IsAlive()){
            GetCurrentMessenger()->AddGroup(name);
		}
    }	
}
  
void MainFrame::OnSignOut(wxCommandEvent& event)
{
	MessengerPanel* panel = GetCurrentMessengerPanel();

	if(panel != NULL && panel->IsAlive()){
		panel->SignOut();
	}
}

void MainFrame::OnCloseAll(wxCommandEvent& event)
{	
	messengerNotebook->DeleteAllPages();
}

void MainFrame::OnOpenMessageHistoryFolder(wxCommandEvent& event)
{
    GetCurrentMessenger()->OpenLogDirectory();
}

void MainFrame::OnOpenReceivedFileFolder(wxCommandEvent& event)
{
    GetCurrentMessenger()->OpenFileDirectory();
}

void MainFrame::OnMessengerPanelChanged(wxNotebookEvent& event)
{
	int pageIndex = event.GetSelection();
	MessengerPanel* panel = (MessengerPanel*) messengerNotebook->GetPage(pageIndex);

	panel->ShowUp(pageIndex);

	panel->LocateFocus();
	UpdateUIStatus();
}

void MainFrame::OnMessengerPanelClosed(wxCommandEvent& event)
{
	MessengerPanel* panel = GetCurrentMessengerPanel();

	if(panel != NULL){
		panel->LocateFocus();
	}
	UpdateUIStatus();

	UpdateTaskBarIcon();
}


void MainFrame::OnClose(wxCloseEvent &event)
{
    //Destroy();
    this->Show(false);
}

void MainFrame::OnActivate(wxActivateEvent& event)
{
	if(event.GetActive()){
		if(this->GetCurrentMessengerPanel() != NULL){
			if(this->GetCurrentMessengerPanel()->CurrentSessionPanel() != NULL){
				this->GetCurrentMessengerPanel()->CurrentSessionPanel()->SetNewMessage(false);
			}
		}
		
	}
}



void MainFrame::OnChangeStatus(wxCommandEvent& event)
{
    int index = event.GetId() - ID_MENU_FILE_STATUS;
    GetCurrentMessenger()->ChangeStatus(MsnDef::STATUS_CODE_ARRAY[index]);
}


void MainFrame::OnOptions(wxCommandEvent& event)
{
    ConfigWindow configWindow(this);
    configWindow.LoadSettings();
    if(configWindow.ShowModal() == wxID_OK){
        configWindow.SaveSettings();
    }
}

void MainFrame::OnTransferWindow(wxCommandEvent& event)
{
    
}


void MainFrame::OnLanguage(wxCommandEvent& event)
{
	int id = event.GetId();

	if(id == ID_MENU_LANGUAGE_CHINESE){
		wxGetApp().InitLanguage(wxLANGUAGE_CHINESE_SIMPLIFIED);
	}else{
		wxGetApp().InitLanguage(wxLANGUAGE_ENGLISH);
	}

	MsnDef::InitText();

	UpdateUIText();
	UpdateUIStatus();
}


void MainFrame::OnQuit(wxCommandEvent &event)
{
    Destroy();
}

void MainFrame::OnAbout(wxCommandEvent &event)
{
   
	//AboutWindow*  aboutWindow = new AboutWindow(this);

	//aboutWindow->ShowModal();

	wxString msg;
	msg<<_("Tuxitty is a simple MSN client application, the current version is ")<<TUX_VERSION << _(".")<<_T("\r\n\r\n");
	msg<<_("If you have any problems or advices, please contact")<<_T(": ");
	msg<<_T("zhzh23@gmail.com") << _(".");

	wxString title;
	title << _("About") << _T(" Tuxitty");
	wxMessageBox(msg, title);

}

void MainFrame::OnDebug(wxCommandEvent& event)
{
	if(logWindow == NULL){
		logWindow = new wxLogWindow(this, _T("test"));
		wxLog::SetActiveTarget(logWindow);
	}

	logWindow->GetFrame()->SetSize(wxSize(600,400));

	logWindow->Show();
}

void MainFrame::OnDebugReceived(wxCommandEvent& event)
{
	wxLogDebug(event.GetString());
}


void MainFrame::SetRecentContactList(const wxArrayString& contactList)
{
    wxMenuItem* item = menuBar->FindItem(ID_MENU_CONTACTS_RECENT);
    wxMenu* parentMenu = item->GetMenu();

    parentMenu->Remove(item);
    delete item->GetSubMenu();

    wxMenu* recentMenu = new wxMenu;
    for(unsigned int i=0;i<contactList.GetCount();i++){
        recentMenu->Append(ID_MENU_CONTACTS_RECENT + i + 1, contactList.Item(i));
    }
    recentMenu->AppendSeparator();
    recentMenu->Append(-1, _("Clear"));
    item->SetSubMenu(recentMenu);

    parentMenu->Insert(parentMenu->GetMenuItemCount(), item);
}

void MainFrame::OnRecentContact(wxCommandEvent& event)
{
    wxMenuItem* item = menuBar->FindItem(event.GetId());
    //messenger->OpenSession(item->GetLabel());
}


void MainFrame::OnToolSearch(wxCommandEvent& event)
{
    if(event.GetEventType() == wxEVT_COMMAND_COMBOBOX_SELECTED ){
        //int index = m_SearchComboBox->GetSelection();

/*
        m_SearchComboBox->SetValue(_T("search"));

        wxString content = m_SearchTextCtrl->GetValue();

        if(content.IsEmpty()) return;

        //wxString url = _T("http://www.google.com/search?q=");
        wxString url = _T("http://www.answers.com/");

        url<<content;

        //wxLaunchDefaultBrowser(url);

        wxExecute(_T("D:\\Program Files\\Mozilla Firefox\\firefox.exe ") + url);
*/
    }
}

#include <curl/curl.h>

void MainFrame::OnTestProxy(wxCommandEvent& event)
{
	CURL *curl = curl_easy_init();

    if(curl) {
        curl_easy_setopt(curl, CURLOPT_URL, "http://www.google.com");

        curl_easy_setopt(curl, CURLOPT_TIMEOUT, 30);
        curl_easy_setopt(curl, CURLOPT_HEADER , 1);
     

		int connectionType = GlobalConfig::GetConnectionType();
		
		if(connectionType == MSN_CONNECTION_HTTP_PROXY){
			wxString proxyAddress = GlobalConfig::GetHttpProxyAddress();
			int proxyPort = GlobalConfig::GetHttpProxyPort();
			wxString userPwd = GlobalConfig::GetHttpProxyUsername() + _T(":") + GlobalConfig::GetHttpProxyPassword();

			wxCharBuffer addrChar = proxyAddress.ToAscii();
			curl_easy_setopt(curl, CURLOPT_PROXY, proxyAddress.mb_str());	
			curl_easy_setopt(curl, CURLOPT_PROXYPORT, proxyPort);
		
			wxCharBuffer userChar = userPwd.ToAscii();
			//curl_easy_setopt(curl, CURLOPT_USERPWD, (unsigned char*)userChar.data());	
		}


        curl_easy_perform(curl);	

	}
}

#include "sha1/wxSHA1.h"

void MainFrame::OnTest(wxCommandEvent& event)
{
	
	wxBitmap bitmap(_T("c://Blueback IT.jpg"), wxBITMAP_TYPE_JPEG);

	wxImage test = bitmap.ConvertToImage().Scale(100, 100);


	bool result = test.SaveFile(_T("c://222.jpg"), wxBITMAP_TYPE_JPEG);

	if(result){
		wxMessageBox(_T("success"));
	}

/*
	SecurityUtil::Sha1(wxFileName(_T("c://xxx.jpg")), buf);

	unsigned char dest[100] = {0};
	StringUtil::base64encode(buf, 20, dest);

	DEBUG(wxString::FromAscii((char*)dest));

	wxMessageBox(MsnUtil::CreateMsnObject(wxFileName(_T("c://xxx.jpg")), _T("tuxitty@hotmail.com"), 3));
*/
	
	//dest = wxString(buf, wxConvUTF8, strlen((char*)buf));
	//wxMessageBox(dest);

/*
   wxFileDialog dialog(this,
                        _T("Testing save file dialog"),
                        wxEmptyString,
                        _T(""),
                        _T(""),
                        wxFD_SAVE|wxFD_OVERWRITE_PROMPT);

    //dialog.SetFilterIndex(1);

	if (dialog.ShowModal() == wxID_OK){}
*/

//	 wxFileDialog fileDialog(this, _("Save file as..."), _T(""), _T(""), _T("*.*"), wxFD_SAVE|wxFD_OVERWRITE_PROMPT);
//    if (fileDialog.ShowModal() == wxID_OK){        
//    }	

	//AddFileTransfer(MsnSession* session, const wxString& cookie, const wxString& fileName, int fileSize)
	//window->AddFileTransfer(NULL, _T("aa"), _T("aaaaaaa.zip"), 1999);
	
//	NotifyWindow* window = new NotifyWindow(this, _T("tuxitty@hotmail.com"), _T("tuxitty"));
//	window->Show();


//	wxString content = _T("VER 1 MSNP10 CVR0\r\n");
//	wxMessageBox(HttpUtil::TestPost(content));

/*
	HTTPTransport *http = new HTTPTransport;
	 if((http->Create() == wxTHREAD_NO_ERROR )){
          if(http->Run() != wxTHREAD_NO_ERROR){
              WARN(_("start thread error"));
          }
     }else{
         WARN(_("start thread error"));
     }
*/

	//FindWindow(2008)->SetFocus();

	//wxFrame* testFrame = new wxFrame(this, -1, _T("test"), wxPoint(50,50), wxSize(800,600));

	//ChatPanel* panel = new ChatPanel(testFrame);

	//wxHtmlWindow* html = new wxHtmlWindow(testFrame);

	//MessengerPanel* panel = new MessengerPanel(testFrame);

	//testFrame->Show();
	

	//BalloonWindow * bbb = new BalloonWindow(this, _T("test"), _T("testttt"));

/*
	ConfigWindow ConfigWindow(this);
    
    if(ConfigWindow.ShowModal() == wxID_OK){

    }
*/

 /*  
	wxPopupTransientWindow* test = new wxPopupTransientWindow(this);
    
	test->SetPosition(wxPoint(50,50));
	test->SetSize(wxSize(200,200));

	test->Popup();
*/


/*
    const char* buf = "aaa\r\nbbb\r\nccc\r\n\r\nddd";
    MessageBuffer mb(20);
    memcpy(mb.GetBuffer(), buf, 20);
   // wxMessageBox(mb.ReadHeader()+_T("!"));
*/




/*
char* c = "PgIAAAIAAABMEwAAAAAAAAAAAABtAHMAbgAuAHQAeAB0AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAIlQTkcNChoKAAAADUlIRFIAAABgAAAAYAgGAAAA4ph3OAAAAqFJREFUeNrt3bFrE2EYx/FcLkeSQeIW7WCspbiJo6uDoi4d7CBSB10srYYMYhy0h2gdirZKi4sWCi46iUjQpmkb0A7FxKipxNWtWBBtakVTEu8P+L3DFZX28j34bi933PNZHm65UGibXPf77U7V6Dm7S3XrjN2tGj1rHVFdOuYkValUKqJyXddShYJ6AQAAAAAAAEDbAzQajU7V0+H971XVuRMt1djAQdl4endNZbrPncunV1Wm8zcuXpA9vN4ns227S5VIJGIqAAAAAAAAAAAgqACTk5Wbqmy22PKTCWDmyV3Z7Stp2cvcB9njsbRs9vm0zARgWdYpleM4u1QAAAAAAAAAAEBQAbLZ+Zbq1cJn2XD/Ydly/bvMdH7lR11mOr/++5fMdL7ZbMoymYzMW0X3qQAAAAAAAAAAgHYDyJcqMtOg/WYC+PZzXWYCaGxsyDYBID/SAQAAAAAAAAAA7QZQfPtRBgAAAAAAAAAAABBsgLnyksw00GtDQ3+lfKEgAwAAAAAAAAAAAPhPAKUlGWsoAAAAAAAAAAAQbIDZyjvZv15D/a6npkEDAAAAAAAAAAAAbBKgVJWxhgIAAAAAAAAAAAH/GLdYk7GGAgAAAAAAAAAAwQYolj/JWEMBAAAAAAAAAIBgA8y8qcr8rqGm9REAAAAAAAAAAABgawLkFssyv+vml7VV2cpaXTa/8PqrKpfPL6vuTYzXVAODgwWVZVnnVZFIZI8KAAAAAAAAAAAIKkAsFkuoHkw9e6TKuu4LVU9v77Qq2dExpfIePWFoROUN6aqhtKE+VTgcPqSKRqM7VQAAAAAAAAAAQFABTD+5t217r8p7ieOGTho6qjINwuuAynt2t8pbFVMqx3GSqng8vkNlmgMAAAAAAAAAALBNAP4Ahre7M6Q6FtgAAAAASUVORK5CYII=";


    char result[1740] = {0};

   StringUtil::Base64_Decode(result, c, 1740);
    //DEBUG(StringUtil::ToHex((unsigned char*)result, 1740));


wxIPV4address addr;
addr.Hostname(wxGetFullHostName());
wxString ipAddr = addr.IPAddress();

DEBUG(wxGetOsDescription());

DEBUG(wxGetFullHostName());
DEBUG(ipAddr);
*/
    //auto connect

    //HttpUtil::getPassport(_(""));
    //wxString src = _("PRP MFN brutu$%20aaaaa%203:1");
    //wxMessageBox(HttpUtil::URLDecode(src));

    //new PromptWindow(this,_("test"),_("test"));

    //MsnMessageFactory::Get().ParseMessage(_("fsdf\r\nContent-Type: text/x-msmsgscontrol\r\n\r\n\r\ndddd"));
}
